package com.zhenyi.xiaohuoche.index;

import java.util.Date;

import com.cjw.model.DBMap;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.utils.AuthUtils;
import com.xhc.common.model.XhcWechat;
import com.zhenyi.xhc.core.XHCController;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class UserController extends XHCController {

	protected final String APP_ID = PropKit.get("XHC_APP_ID", "wx54277a43aad4df57");
	protected final String APP_SECRET = PropKit.get("XHC_APP_SECRET", "b0442f55643cfa9309b445ff75945cd9");
	private final String code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code";

	public void auth() {
		String code = getPara("code");
		String country = getPara("country");
		Integer gender = getParaToInt("gender", 0);
		String province = getPara("province");
		String avatarUrl = getPara("avatarUrl");
		String nickName = getPara("nickName");
		String url = StrFormatter.format(code2SessionUrl, APP_ID, APP_SECRET, code);
		// System.out.println(url);
		String response = HttpKit.get(url);
		// System.out.println(response);
		JSONObject jsonObject = JSONUtil.parseObj(response);
		String openId = jsonObject.getStr("openid");
		String session_key = jsonObject.getStr("session_key");
		String unionid = jsonObject.getStr("unionid");
		Integer errcode = jsonObject.getInt("errcode");
		if (errcode != null) {
			String errmsg = jsonObject.getStr("errmsg");
			LogKit.warn("jscode2session error " + errmsg);
			renderFailure();
			return;
		}
		XhcWechat wechat = XhcWechat.dao.findByOpenId(openId);
		if (wechat == null) {
			wechat = new XhcWechat();
			wechat.save();
			wechat.setOpenId(openId);
		}
		wechat.setSessionKey(session_key);
		wechat.setCountry(country);
		wechat.setProvince(province);
		wechat.setNickName(nickName);
		wechat.setAppid(APP_ID);
		wechat.setAvatarUrl(avatarUrl);
		wechat.setGender(gender);
		wechat.setLastLogin(new Date());
		wechat.update();
		DBMap map = new DBMap();
		String token = AuthUtils.login(String.valueOf(wechat.getId()), this);
		map.put("token", token);
		map.put("openId", wechat.getOpenId());
		renderSuccess(map);
	}

	public void login() {

	}
}
